package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-cloud-disk/common"
	"go-cloud-disk/common/cache"
	"go-cloud-disk/common/util"
	"go-cloud-disk/internal/api"
	"go-cloud-disk/internal/dao"
)

// 管理用户登录的服务
type UserLoginService struct {
	UserName string `form:"userName" json:"userName" binding:"required,email"`
	Password string `form:"Password" json:"Password" binding:"required,min=4,max=64"`
}

// 用户登录
func UserLogin(c *gin.Context) {
	var service UserLoginService
	if err := c.ShouldBindJSON(&service); err == nil {
		res := user.Login(c)
		c.JSON(200, res)
	} else {
		c.JSON(200, common.ErrorResponse(err))
	}
}

// Login 用户登录函数
func (service *UserLoginService) Login(c *gin.Context) common.Response {
	expectedUser, err := dao.GetUserByEmail(service.UserName)
	// 一系列校验
	if err != nil {
		return common.Err(common.CodeCredentialInvalid, "用户邮箱或密码错误", err)
	}
	if authOK, _ := expectedUser.CheckPassword(service.Password); !authOK {
		return common.Err(common.CodeCredentialInvalid, "用户邮箱或密码错误", nil)
	}
	if expectedUser.Status == model.Baned || expectedUser.Status == model.OveruseBaned {
		return common.Err(403, "该账号已被封禁", nil)
	}
	if expectedUser.Status == model.NotActivicated {
		return common.Err(403, "该账号未激活", nil)
	}

	if expectedUser.TwoFactor != "" {
		// 需要二步验证
		util.SetSession(c, map[string]interface{}{
			"2fa_user_id": expectedUser.ID,
		})
		return common.Response{Code: 203}
	}

	//登陆成功，清空并设置session
	util.SetSession(c, map[string]interface{}{
		"user_id": expectedUser.ID,
	})

	return common.BuildUserResponse(expectedUser)
}

// GetUserAvatar 获取用户头像
func GetUserAvatar(c *gin.Context) {

}

// 查看给定用户的分享
func GetUserShare(c *gin.Context) {

}

// 重设密码
func Reset(req api.UserResetService) common.Response {
	// 取得原始用户ID
	uid, err := common.DecodeHashID(req.ID, common.UserID)
	if err != nil {
		return common.Err(common.CodeNotFound, "重设链接无效", err)
	}

	// 检查重设会话
	resetSession, exist := cache.Get(fmt.Sprintf("user_reset_%d", uid))
	if !exist || resetSession.(string) != req.Secret {
		return common.Err(common.CodeNotFound, "链接已过期", err)
	}

	// 重设用户密码
	user, err := dao.GetActiveUserByID(uid)
	if err != nil {
		return common.Err(common.CodeNotFound, "用户不存在", err)
	}

	user.SetPassword(req.Password)
	if err := user.Update(map[string]interface{}{"password": req.Password}); err != nil {
		return common.DBErr("无法重设密码", err)
	}

	cache.Deletes([]string{fmt.Sprintf("%d", uid)}, "user_reset_")
	return common.Response{}
}
